<template>
  <div class="animate__animated animate__fadeIn">
    <!-- 默认显示层 -->
    <el-card>
      <!--查询部分-->
      <div class="top-container">
        <!--搜索部分-->
        <div class="search-container" v-show="searchShow">
          <el-input
              style="width: 40%;margin-right: 10px"
              placeholder="请输入需要查询的用户名或昵称..."
              size="small"
              prefix-icon="el-icon-search"
              clearable
              @clear="clearMenuName"
              v-model="searchCondition.name">
          </el-input>
          <el-select v-model="searchCondition.isDisable"
                     clearable
                     size="small"
                     @clear="clearMenuStatus"
                     placeholder="请选择用户状态">
            <el-option :key="1" label="禁用" :value="1"/>
            <el-option :key="0" label="正常" :value="0"/>
          </el-select>
          <el-button type="primary"
                     size="small"
                     icon="el-icon-search"
                     @click="searchUserInfo"
                     style="margin-left: 10px">搜索
          </el-button>
        </div>
        <!--添加部分-->
        <div class="save-container">
          <!--添加-->
          <div class="save-box">
            <el-button type="primary" size="small" plain icon="el-icon-plus" @click="addUserShow">添加用户
            </el-button>
          </div>
          <!--关闭-->
          <div class="close-box">
            <el-tooltip content="关闭查询" placement="bottom">
              <el-button type="primary" size="small" plain circle icon="el-icon-search"
                         @click="searchShow = !searchShow"/>
            </el-tooltip>
            <el-tooltip content="刷新数据" placement="bottom">
              <el-button type="success" size="small" plain circle icon="el-icon-refresh" @click="initData"/>
            </el-tooltip>
            <el-tooltip content="显隐列" placement="bottom">
              <el-button type="warning" size="small" plain circle icon="el-icon-menu" @click="transferVisible = true"/>
            </el-tooltip>
          </div>
        </div>
      </div>
      <!--显隐列 弹出层-->
      <el-dialog
          title="显隐列设置"
          :visible.sync="transferVisible"
          width="45%"
          append-to-body
          center>
        <el-transfer
            v-model="transferValue"
            :data="transferData"
            :titles="transferTitles">
        </el-transfer>
      </el-dialog>
      <!--数据部分-->
      <el-table
          :data="userList"
          border
          highlight-current-row
          style="width: 100%">
        <el-table-column
            label="序号"
            width="55">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column
            v-if="!transferValue.includes('用户ID')"
            prop="userId"
            label="用户ID"
            align="center"
            width="70">
        </el-table-column>
        <el-table-column
            v-if="transferValue.includes('用户账号（第三方token）')"
            prop="username"
            label="用户名称"
            align="center"
            width="120">
        </el-table-column>
        <el-table-column
            v-if="transferValue.includes('用户昵称')"
            prop="nickname"
            label="昵称"
            align="center"
            width="120">
        </el-table-column>
        <el-table-column
            v-if="transferValue.includes('用户头像')"
            prop="avater"
            label="用户头像"
            align="center"
            width="80">
          <template slot-scope="scope">
            <img class="el-avatar--circle el-avatar--medium" :src="scope.row.avatar" alt="用户头像">
          </template>
        </el-table-column>
        <el-table-column
            v-if="transferValue.includes('用户邮箱')"
            prop="email"
            label="邮箱"
            align="center"
            width="200">
        </el-table-column>

        <el-table-column
            v-if="transferValue.includes('用户电话')"
            prop="phoneNum"
            label="电话号码"
            align="center"
            width="120">
        </el-table-column>

        <el-table-column
            v-if="transferValue.includes('用户性别')"
            prop="gender"
            label="性别"
            align="center"
            :formatter="formatGender"
            width="120">
        </el-table-column>

        <el-table-column
            v-if="transferValue.includes('登录地区')"
            prop="loginAddress"
            label="登录地区"
            align="center"
            width="120">
        </el-table-column>

        <el-table-column
            v-if="transferValue.includes('登陆ip')"
            prop="loginIp"
            label="登陆ip"
            align="center"
            width="120">
        </el-table-column>

        <el-table-column
            v-if="transferValue.includes('浏览器')"
            prop="browser"
            label="浏览器"
            align="center"
            width="120">
        </el-table-column>

        <el-table-column
            v-if="transferValue.includes('最高权限角色')"
            prop="consumerLevel"
            label="最高权限角色"
            align="center"
            width="120">
        </el-table-column>

        <el-table-column
            v-if="transferValue.includes('是否被禁用')"
            prop="isDisable"
            label="用户状态"
            align="center"
            width="100">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.isDisable === false" type="success">正常</el-tag>
            <el-tag v-if="scope.row.isDisable === true" type="danger">失效</el-tag>
          </template>
        </el-table-column>

        <el-table-column
            v-if="transferValue.includes('备注信息')"
            prop="remark"
            label="备注信息"
            align="center"
            width="120">
        </el-table-column>

        <el-table-column
            label="操作"
            align="center"
            width="120">
          <template slot-scope="scope">
            <el-button @click="handleClick(scope.row)" type="text" size="small">编辑</el-button>
            <el-button @click="handleViewClick(scope.row)" type="text" size="small">查看</el-button>
            <el-button @click="deleteUser(scope.row)" type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页-->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[1, 5, 10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageTotal">
      </el-pagination>
    </el-card>
    <!--新增 弹出层-->
    <el-drawer
        :title="userFormTitle"
        :visible.sync="saveUserVisible"
        append-to-body
        direction="rtl"
        size="28%"
        :before-close="leave">
      <div class="save-container">
        <el-form ref="userFormCheck"
                 :rules="rule"
                 :model="userInfoForm"
                 :disabled="userInfoFormStatus"
                 label-width="90px"
                 class="demo-ruleForm">
          <el-form-item label="用户ID" v-if="userInfoForm.userId !== -1">
            <el-tag type="success">{{ userInfoForm.userId }}</el-tag>
          </el-form-item>
          <el-form-item label="用户名" prop="username">
            <el-input v-model="userInfoForm.username"
                      border
                      label="user"
                      placeholder="请输入用户名..."/>
          </el-form-item>
          <el-form-item label="用户昵称" prop="nickname">
            <el-input v-model="userInfoForm.nickname"
                      border
                      label="user"
                      placeholder="请输入用户昵称..."/>
          </el-form-item>
          <el-form-item label="角色" prop="roleId">
            <el-select
                v-model="userInfoForm.roleId"
                filterable
                placeholder="请选择用户角色">
              <el-option
                  v-for="item in roleList"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="电话号码" prop="phoneNum">
            <el-input type="number"
                      size="small"
                      border
                      label="user"
                      @mousewheel.native.prevent
                      v-model.number="userInfoForm.phoneNum"/>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input type="email" size="small"
                      border
                      label="user"
                      v-model="userInfoForm.email"/>
          </el-form-item>
          <el-form-item label="密码"
                        prop="password"
                        align="center" v-if="isShowPasswordInput">
            <el-input type="text"
                      border
                      label="user"
                      placeholder="请输入密码..." v-model="userInfoForm.password"/>
          </el-form-item>
          <el-form-item label="确认密码"
                        prop="confirmPwd"
                        align="center" v-if="isShowPasswordInput">
            <el-input type="text"
                      border
                      label="user"
                      placeholder="请输入确认密码..." v-model="userInfoForm.confirmPwd"/>
          </el-form-item>

          <el-form-item label="性别" align="center" prop="gender">
            <el-select v-model.number="userInfoForm.gender"
                       clearable
                       size="small"
                       border
                       label="user"
                       placeholder="用户性别">
              <el-option :key="1" label="女" :value="1"/>
              <el-option :key="0" label="男" :value="0"/>
              <el-option :key="-1" label="其他" :value="-1"/>
            </el-select>
          </el-form-item>
          <el-form-item label="头像地址" align="center">
            <el-input type="text"
                      border
                      label="user"
                      placeholder="请输入头像地址..." v-model="userInfoForm.avatar"/>
          </el-form-item>
          <el-form-item label="备注信息" align="center">
            <el-input type="textarea" :rows="3" placeholder="请输入备注信息..." v-model="userInfoForm.remark"/>
          </el-form-item>

          <el-form-item align="center">
            <el-button icon="el-icon-sunny" size="small" type="success" plain @click="saveUserContent('userFormCheck')">
              确定
            </el-button>
            <el-popconfirm
                v-if="userInfoForm.userId === -1"
                style="margin-left: 10px"
                title="确定要重置用户信息吗？"
                @confirm="clearUserInfoForm">
              <el-button icon="el-icon-refresh" size="small" type="warning" plain slot="reference">重置</el-button>
            </el-popconfirm>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>
  </div>
</template>

<script>

import {
  getUserList,
  getUserListByCondition,
  addUserInfo,
  deleteUserInfo,
  updateUserInfo,
  transferUserData
} from "../../../api/consumer/consumerApi";

import {getRoleList, searchRoleByCondition} from "../../../api/consumer/roleApi";
import {messageInfo} from "@/utils/MessageInfo";
import {resultCheck} from "@/utils/result";
import router from "@/router";
import {transferMenuData, transferTitles} from "@/assets/const/menu";


export default {
  name: "userInfo",
  data() {
    return {
      loading: true,      //表单加载
      // ==================  查询条件 ================================
      searchShow: true,   //查询功能是否开启
      searchCondition: {   //查询条件
        name: '',
        isDisable: '',
      },
      // ==================  控件显示控制 ================================
      saveUserVisible: false,  //是否显示表单信息
      // ================== 穿梭表单数据 ================================
      transferTitles: transferTitles(),  //穿梭表单title
      transferValue: ["用户头像", "用户昵称", "用户性别",  "用户电话", "用户邮箱", "是否被禁用", "备注信息"],               //穿梭表单选中数据
      transferData: transferUserData(),      //穿梭表单数据
      transferVisible: false,            //显隐列是否开启
      // ==================  用户信息列表 ================================
      userList: [
        {
          consumerLevel: "",
        }
      ],
      // ==================  分页信息 ================================
      pageTotal: 0,  // 页面总数
      currentPage: 1,  // 当前页码
      pageSize: 20, // 页面大小
      // ================== 新增/修改用户表单控制 ================================
      rule: {
        username: [{required: true, message: '用户名不能为空！', trigger: 'blur'}],
        nickname: [{required: true, message: '用户昵称！', trigger: 'blur'}],
        roleId: [{required: true, message: '角色信息不能为空！', trigger: 'blur'}],
        phoneNum: [{validator: this.validatePhoneNumber, required: true, trigger: 'blur'}],
        password: [{required: true, message: '密码不能为空！', trigger: 'blur'}],
        confirmPwd: [{validator: this.validateConfirmPassword, required: true, trigger: 'blur'}],
        gender: [{required: true, message: '性别不能为空！', trigger: 'blur'}],
        email: [{validator: this.validateEmail, required: true, trigger: 'blur'}],
      },
      userInfoForm: {
        userId: -1,
        username: "",
        nickname: "",
        remark: "",
        roleId: "",
        phoneNum: "",
        password: "",
        confirmPwd: "",
        gender: "",
        email: "",
        avatar: "",
      },
      userFormTitle: "用户信息表单",
      isShowPasswordInput: false,  // 是否显示密码输入框
      userInfoFormStatus: false, // 表单是否禁用编辑
      userInfoFormType: "user",
      roleList: [],
    }

  },
  mounted() {
    this.initData();
  },
  methods: {
    //=======================  校验规则 start  ===========================
    //=======================  校验邮箱  ===========================
    validateEmail(rule, value, callback) {
      const reg = /^([a-zA-Z0-9]+[-_\.]?)+@[a-zA-Z0-9]+\.[a-z]+$/;
      if (value === '') {
        callback(new Error('请输入邮箱地址！'))
      } else if (!reg.test(value)) {
        callback(new Error('请输入有效的邮箱地址！'));
      } else {
        callback()
      }
    },
    //=======================  校验表单输入的是电话号码  ===========================
    validatePhoneNumber(rule, value, callback) {
      const reg = /^1[3456789]\d{9}$/;
      if (value === '') {
        callback(new Error('请输入11位的电话号码！'))
      } else if (!reg.test(value)) {
        callback(new Error('请输入有效的手机号码'));
      } else {
        callback()
      }

    },
    //=======================  校验表单输入的密码  ===========================
    validateConfirmPassword(rule, value, callback) {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.userInfoForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    },
    //=======================  校验规则 end  ===========================
    //=======================  数据相关 start  =========================
    //=======================  数据初始化  ===========================
    initData() {
      this.loading = true;
      const param = {
        "current": this.currentPage,
        "size": this.pageSize
      };
      getUserList(param).then(res => {
        if (res.status) {
          this.userList = res.data.data;
          this.pageTotal = res.data.total;
        } else {
          messageInfo({type: "error", message: res.message});
        }
        this.loading = false;
      });
    },
    //=======================  新增/修改菜单部分  ===========================
    leave() {
      // 如果表格不是禁用状态离开，进行提醒！
      if (!this.userInfoFormStatus){
        this.$confirm('数据不会临时保存，切勿离开此界面！')
            .then(_ => {
              this.userInfoForm = {userId: -1};
              this.saveUserVisible = false;
            });
      }else {
        this.userInfoForm = {userId: -1};
        this.saveUserVisible = false;
      }
    },
    //=======================  清空菜单状态  ===========================
    clearMenuStatus() {
      this.initData();
    },
    //=======================  清空菜单名称  ===========================
    clearMenuName() {
      this.initData();
    },
    sortRoleId(a, b) {
      return a.roleId - b.roleId;
    },
    //=======================  点击编辑用户信息  ===========================
    handleClick(row) {
      // 取消禁用表单
      this.userFormTitle = "编辑用户信息";
      this.userInfoFormStatus = false;
      this.isShowPasswordInput = false;

      this.userInfoForm = {
        userId: row.userId,
        username: row.username,
        nickname: row.nickname,
        remark: row.remark,
        roleId: row.roleId,
        phoneNum: row.phoneNum,
        gender: row.gender,
        email: row.email,
        avatar: row.avatar,
        roleList: row.roleList,
      };
      this.initRoleList();
      this.userInfoForm.roleList.sort(this.sortRoleId);
      this.userInfoForm.roleId = this.userInfoForm.roleList[0].roleId
      this.userInfoForm.gender = Number.parseInt(this.userInfoForm.gender)
      this.saveUserVisible = true;
    },
    //=======================  当点击查看时  ===========================
    handleViewClick(row) {
      this.handleClick(row);
      this.userFormTitle = "查看用户信息";
      // 禁用表单
      this.userInfoFormStatus = true
      this.isShowPasswordInput = false;

    },
    //=======================  删除用户信息  ===========================
    deleteUser(row) {
      deleteUserInfo(row.userId).then(res => {
        if (res.status) {
          resultCheck(res, true);
          messageInfo({type: "success", message: res.message});
        } else {
          messageInfo({type: "error", message: res.message});
        }
        this.loading = false;
      });
      this.initData();
    },
    //=======================  boolean 格式化  ===========================
    formatDelFlag: function (row, index) {
      let ret = '';
      if (row.isDisable === false) {
        ret = "是" //根据自己的需求设定
      } else {
        ret = "否"
      }
      return ret;
    },
    formatGender: function (row, index) {
      let ret = '其他';
      if (row.gender === "0") {
        ret = "男" //根据自己的需求设定
      } else if (row.gender === "1") {
        ret = "女"
      }
      return ret;
    },
    addUserShow() {
      this.userFormTitle = "新增用户信息";
      this.isShowPasswordInput = true;
      this.saveUserVisible = true;
      this.userInfoFormStatus = false;
      this.initRoleList();
    },
    //======================= 初始化角色列表  ===========================
    initRoleList() {
      getRoleList().then(res => {
        if (res.status) {
          this.roleList = res.data;
        } else {
          messageInfo({type: "error", message: res.message});
        }
      });
    },
    //======================= 处理当前页面大小改变  ===========================
    handleSizeChange(val) {
      this.pageSize = val
      var param = {
        "current": this.currentPage,
        "size": this.pageSize
      }
      getUserList(param).then(res => {
        if (res.status) {
          this.userList = res.data.data;
          this.pageTotal = res.data.total;
        } else {
          messageInfo({type: "error", message: res.message});
        }
        this.loading = true;
      });
    },
    //======================= 处理当前页面改变  ===========================
    handleCurrentChange(val) {
      this.currentPage = val
      var param = {
        "current": this.currentPage,
        "size": this.pageSize
      }
      getUserList(param).then(res => {
        if (res.status) {
          this.userList = res.data.data;
          this.pageTotal = res.data.total;
        } else {
          messageInfo({type: "error", message: res.message});
        }
        this.loading = true;
      });
      console.log(`当前页: ${val}`);
    },

    //======================= 查询用户信息  ===========================
    searchUserInfo() {
      const param = {
        "current": this.currentPage,
        "size": this.pageSize,
        "name": this.searchCondition.name,
        "isDisable": this.searchCondition.isDisable
      };
      getUserListByCondition(param).then(res => {
        if (res.status) {
          this.userList = res.data.data;
          this.pageTotal = res.data.total;
        } else {
          messageInfo({type: "error", message: res.message});
        }
        this.loading = true;
      });
    },

    //======================= 查询用户角色信息  ===========================
    queryRoleInfoSearch(queryString, cb) {
      var param = {
        "name": queryString,
        "isDisable": false
      };
      searchRoleByCondition(param).then(res => {
        if (res.status) {
          this.roleList = res.data;
        } else {
          messageInfo({type: "error", message: res.message});
        }
      });
    },
    //======================= 查询用户信息  ===========================
    saveUserContent(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 添加用户信息
          if (this.userInfoForm.userId === -1) {
            addUserInfo(this.userInfoForm).then(res => {
              resultCheck(res, true);
            });
            this.initData();
          } else {
            // 更新用户信息
            updateUserInfo(this.userInfoForm).then(res => {
              if (res.status) {
                resultCheck(res, true);
                messageInfo({type: "success", message: res.message});
              } else {
                messageInfo({type: "error", message: res.message});
              }
            })
          }

          this.saveUserVisible = false; // 关闭表单侧边栏
          this.isShowPasswordInput = false;
          // 更新用户数据信息
          this.loading = true;
          this.clearUserInfoForm();
          this.initData();
        } else {

        }
      });
    },
    //  清空表单信息
    clearUserInfoForm() {
      this.userInfoForm = {
        userId: -1,
      };
    },
    //=======================  数据相关 end  =========================
  }

}
</script>

<style>
.top-container {
  width: 100%;
}

.search-container {
  width: 100%;
  display: flex;
  justify-content: left;
}

.save-container {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}

.el-button--text {
  color: #70b2f8;
  font-size: 12px;
}

input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
  margin: 0;
  -moz-appearance: textfield;
}
</style>